
package org.example.executor.parameter;

import cn.hutool.db.meta.JdbcType;
import org.example.config.Configuration;
import org.example.mapping.BoundSql;
import org.example.mapping.MappedStatement;
import org.example.mapping.ParameterMapping;
import org.example.type.TypeHandler;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * @author Clinton Begin
 * @author Eduardo Macarron
 */
public class DefaultParameterHandler implements ParameterHandler {

  //private final TypeHandlerRegistry typeHandlerRegistry;

  private final MappedStatement mappedStatement;
  private final Object parameterObject;
  private final BoundSql boundSql;
  private final Configuration configuration;

  public DefaultParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
    this.mappedStatement = mappedStatement;
    this.configuration = mappedStatement.getConfiguration();
    //this.typeHandlerRegistry = mappedStatement.getConfiguration().getTypeHandlerRegistry();
    this.parameterObject = parameterObject;
    this.boundSql = boundSql;
  }

  @Override
  public Object getParameterObject() {
    return parameterObject;
  }

  @Override
  public void setParameters(PreparedStatement ps) {
    //ps.get
    List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();

    for (int i = 0; i < parameterMappings.size(); i++) {
      ParameterMapping parameterMapping = parameterMappings.get(i);
      Object propertyValue = parameterObject;
      TypeHandler typeHandler = parameterMapping.getTypeHandler();
      try {
        typeHandler.setNonNullParameter(ps,i+1,propertyValue,parameterMapping.getJdbcType());
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
  }

}
